package com.codefish.service.impl;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codefish.entity.CapitalAccount;
import com.codefish.entity.OutMoney;
import com.codefish.entity.OutMoneyType;
import com.codefish.entity.SysUserTokenEntity;
import com.codefish.mapper.OutMoneyDao;
import com.codefish.service.CapitalAccountService;
import com.codefish.service.OutMoneyService;
import com.codefish.service.OutMoneyTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service("outMoneyService")
public class OutMoneyServiceImpl extends ServiceImpl<OutMoneyDao, OutMoney> implements OutMoneyService {

    @Autowired
    private OutMoneyTypeService outMoneyTypeService;

    @Autowired
    private CapitalAccountService capitalAccountService;

    /**
     * 新增
     *
     * @param outMoney
     * @return
     */
    @Override
    public int saveOne(OutMoney outMoney) {

        boolean flag = this.save(outMoney);
        if (flag) {
            return outMoney.getId();
        }

        return -1;
    }

    /**
     * 修改
     *
     * @param outMoney
     * @return
     */
    @Override
    public boolean updateOne(OutMoney outMoney) {

        boolean flag = this.updateById(outMoney);

        if (flag) {
            return true;
        }
        return false;
    }

    /**
     * 确认当前用户是否可以访问此条支出记录
     *
     * @param userId
     * @param id
     * @return
     */
    @Override
    public boolean checkQualification(Long userId, Integer id) {

        SysUserTokenEntity user = SysUserTokenServiceImpl.getUserById(userId);
        if (ObjectUtils.isEmpty(user) || ObjectUtils.isEmpty(user.getFamilyId())) {
            return false;
        }
        Integer familyId = user.getFamilyId();

        QueryWrapper<OutMoney> qw = new QueryWrapper<>();
        qw.eq("family_id", familyId).eq("id", id);

        Integer count = baseMapper.selectCount(qw);

        if (count > 0) {
            return true;
        }

        return false;
    }

    /**
     * 根据id获取详情
     *
     * @param id
     * @return
     */
    @Override
    public OutMoney getItemById(Integer id) {
        OutMoney retEntity = new OutMoney();

        OutMoney outMoney = baseMapper.selectById(id);

        if (ObjectUtils.isEmpty(outMoney)) {
            return retEntity;
        }

        return outMoney;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteOne(Integer id) {

        OutMoney outMoney = new OutMoney();
        outMoney.setId(id);
        outMoney.setIsDel(1);

        boolean deleteFlag = this.updateById(outMoney);
        if (deleteFlag) {
            return true;
        }

        return false;
    }

    /**
     * 条件分页查询
     *
     * @param familyId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public IPage<OutMoney> getPageByParams(Integer familyId, Integer pageNo, Integer pageSize) {

        Page<OutMoney> page = new Page<>(pageNo, pageSize);

        QueryWrapper<OutMoney> qw = new QueryWrapper<>();
        qw.eq("state", 1).ne("is_del", 1);
        qw.eq("family_id", familyId);
        qw.orderByDesc("id");

        IPage<OutMoney> retPage = baseMapper.selectPage(page, qw);

        this.setNameByCode(retPage);
        return retPage;
    }

    /**
     * setNameByCode
     *
     * @param retPage
     */
    private IPage<OutMoney> setNameByCode(IPage<OutMoney> retPage) {
        List<Integer> capitalAccountIds = retPage.getRecords()
                .stream()
                .map(OutMoney::getCapitalAccountId)
                .filter(one -> !ObjectUtils.isEmpty(one))
                .collect(Collectors.toList());

        List<Integer> outMoneyTypeList = retPage.getRecords()
                .stream()
                .map(OutMoney::getOutMoneyType)
                .filter(one -> !ObjectUtils.isEmpty(one))
                .collect(Collectors.toList());
        ;

        // 查询账户名称
        List<CapitalAccount> capitalAccounts = capitalAccountService.selectListByIds(capitalAccountIds);

        // 支出类型
        List<OutMoneyType> outMoneyTypes = outMoneyTypeService.selectListByIds(outMoneyTypeList);

        for (OutMoney outMoney : retPage.getRecords()) {

            // 匹配账号名称
            if (!ObjectUtils.isEmpty(outMoney.getCapitalAccountId())) {
                Integer capitalAccountId = outMoney.getCapitalAccountId();
                CapitalAccount capitalAccount = capitalAccounts.stream().filter(one -> Objects.equals(one.getId(), capitalAccountId)).findFirst().orElse(null);
                if (null != capitalAccount) {
                    outMoney.setCapitalAccountName(StringUtils.isEmpty(capitalAccount.getAccountName()) ? null : capitalAccount.getAccountName());
                }
            }
            // 匹配支出类型名称
            if (!ObjectUtils.isEmpty(outMoney.getOutMoneyType())) {
                Integer outMoneyType = outMoney.getOutMoneyType();
                OutMoneyType type = outMoneyTypes.stream().filter(one -> Objects.equals(one.getId(), outMoneyType)).findFirst().orElse(null);
                if (null != type) {
                    outMoney.setOutMoneyTypeName(StringUtils.isEmpty(type.getTypeName()) ? null : type.getTypeName());
                }
            }
        }

        return retPage;
    }
}